import { AutoComplete, Card, Col, Empty, Input, Tree } from 'antd';
import React, { ChangeEvent, useContext, useState } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { UserManageContext, autoOptionRole } from '../hooks';
import { clickScrollToAnchor, loopArray, searchChangeColor, transltateFn } from '@/utils';
import MyIcon from '@/components/MyIcon';
import pageStyles from '@/common/pageLayout.less';

interface IOpenRoleLeftTreeModalAPI {
  roleInfoList: Record<string, any>[];
  setCheckRoleRowsInfo: (rowInfo: Record<string, any>) => void;
  checkRoleRowsInfo: {
    roleCheckKeys: string[];
    roleCheckRows: Record<string, any>[];
  };
}
export const OpenRoleLeftTreeModal: React.FC<IOpenRoleLeftTreeModalAPI> = ({ roleInfoList, setCheckRoleRowsInfo, checkRoleRowsInfo }) => {
  /** 引入上下文 */
  const { userFixCls } = useContext(UserManageContext);

  /** 左侧树 */
  const [leftTreeInfo, setLeftTreeInfo] = useState<Record<string, any>>({
    searchValueLeft: '',
    autoExpandParentLeft: false,
    expandedKeysLeft: [],
  });

  /** 处理树数据 */
  const handleLeftTree = (treeList: Record<string, any>[]) => {
    return treeList?.map((item) => {
      const titleTree = searchChangeColor(item?.name, leftTreeInfo?.searchValueLeft);
      return {
        ...item,
        title: (
          <div style={{ display: 'flex', alignItems: 'center' }} id={item?.id + 'userControll-roleModal'}>
            <MyIcon style={{ marginRight: 5 }} type="icon-lianxiren" />
            &nbsp;
            {titleTree}
          </div>
        ),
        key: item?.id,
        children: item?.children?.length > 0 ? handleLeftTree(item?.children) : [],
      };
    });
  };

  /**
   * 保存选中的值
   * @param checkedKeys
   * @param treeNodes
   */
  const onTreeSelect = (checkedKeys: any, treeNodes: any) => {
    setCheckRoleRowsInfo({
      roleCheckKeys: checkedKeys?.checked,
      roleCheckRows: treeNodes?.checkedNodes,
    });
  };

  // 点击展开关闭树
  const onTreeExpand = (e) => {
    setLeftTreeInfo((prev: Record<string, any>) => {
      return {
        ...prev,
        autoExpandParentLeft: false,
        expandedKeysLeft: e,
      };
    });
  };

  /** 左侧树搜索值改变  */
  const onSelectAuto = (value: string, option: any) => {
    // const promise = new Promise((resolve) => {
    const optionId = option?.key;
    const rowObj = option?.itemrowobj;
    const targetNode = loopArray(roleInfoList); //平铺的树
    let openTreeIds = transltateFn(targetNode, rowObj?.pID);

    setLeftTreeInfo((prev: Record<string, any>) => {
      return {
        ...prev,
        searchValueLeft: value,
        autoExpandParentLeft: true,
        expandedKeysLeft: openTreeIds,
      };
    });

    setTimeout(() => {
      clickScrollToAnchor(optionId + 'userControll-roleModal');
    }, 1000);
  };

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    const inputValue: string = e.target.value;
    setLeftTreeInfo((prev: Record<string, any>) => {
      return {
        ...prev,
        searchValueLeft: inputValue ? inputValue : '',
      };
    });
  };

  return (
    <Col
      span={11}
      style={{
        height: document.body.clientHeight * 0.4,
        overflow: 'hidden',
      }}
    >
      <Card
        bordered
        className={`${userFixCls}userRoleCard`}
        title={
          <>
            <AutoComplete
              style={{ width: '100%' }}
              options={autoOptionRole(roleInfoList, leftTreeInfo?.searchValueLeft, 'name')}
              notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
              onSelect={onSelectAuto}
            >
              <Input suffix={<SearchOutlined />} onChange={onInputChange} placeholder="请按名称搜索" allowClear />
            </AutoComplete>
          </>
        }
      >
        <ScrollBarLayout style={{ padding: '5px 10px' }}>
          {roleInfoList && roleInfoList?.length > 0 ? (
            <Tree
              treeData={handleLeftTree(roleInfoList)}
              blockNode={true}
              checkable={true}
              autoExpandParent={leftTreeInfo?.autoExpandParentLeft}
              checkedKeys={checkRoleRowsInfo?.roleCheckKeys}
              onCheck={onTreeSelect}
              expandedKeys={leftTreeInfo?.expandedKeysLeft}
              onExpand={onTreeExpand}
              checkStrictly={true}
            />
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </ScrollBarLayout>
      </Card>
    </Col>
  );
};
